package com.tfswx.jcyw.sqlmodel.api.util;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tfswx.jcyw.sqlmodel.api.bean.table.Select;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Collection;

/**
 * @author 张述江
 * @date 2023/9/16
 */
public class ObjectUtil {

    public static String objToString(Object obj) {

        JSONObject jsonObject = objToJson(obj);

        System.out.println(obj);
        return "";
    }

    private static JSONObject objToJson(Object obj) {
        return objToJson(obj, null);
    }

    private static JSONObject objToJson(Object obj, String propertyName) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("propertyName", propertyName);
        jsonObject.put("value", JSONObject.toJSONString(obj));
        // 为空则只记录属性名称和空值（防止存在默认值的情况）
        if (obj == null) {
            return jsonObject;
        }
        Class<?> aClass = obj.getClass();
        jsonObject.put("className", aClass.getName());
        if (aClass.getName().startsWith("java.lang")) {
            return jsonObject;
        }

        if (obj instanceof Collection) {
            // 如果是列表，则使用属性配置

        } else {
            JSONArray children = new JSONArray();
            for (Field declaredField : aClass.getDeclaredFields()) {
                if (declaredField.getModifiers() == (Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL)) {
                    continue;
                }
                String name = declaredField.getName();
                System.out.println(name);
                Object property = BeanUtil.getProperty(obj, name);
                children.add(objToJson(property, name));
            }
            jsonObject.put("children", children);
        }
        return jsonObject;
    }

    public static Select stringToObj(String s) {
        return null;
    }


    public static void main(String[] args) {
        /*

       {a:b,c:[""],d:[{e:"",f:{"g":"h"}}],i:{j:"k"}}

        * */

        /*





         * */


    }
}
